package com.sxkj.gis.wms.GetFeatureInfo.controller;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sxkj.gis.wms.GetFeatureInfo.service.GetFeatureInfoService;
import com.sxkj.gis.wms.bean.WmsParams;
import com.sxkj.gis.wms.comm.service.WmsCommService;
import com.sxkj.gis.wms.getmap.controller.GetMapController;
/**
 * WMS_featureInfo 请求 控制类
 * @author admin
 *
 */
@Controller
public class GetFeatureInfoController {
	@Resource
	private GetFeatureInfoService getFeatureInfoService;
	@Resource
	private WmsCommService wmsCommService;
	/**
	 * 图片保存的根路径
	 */
	private static String  basePath = GetFeatureInfoController.class.getClassLoader().getResource("data/").getPath();
	
	/**
	 * 图片保存的根路径下的目录
	 */
	private static String saveDir = "img";
	
	private static Integer i = 1;
	
	private Map<Integer,String> textMap = new HashMap<Integer,String>();
	
	@ResponseBody
	@RequestMapping(value="WMS_featureInfo.url.do")
	public Integer  getFeatureInfo(HttpSession session, HttpServletRequest rq, HttpServletResponse rp,WmsParams wmsParams){
		String textName = System.currentTimeMillis()+".txt";
		textMap.put(i, textName);
		try {
			byte[] buffer= getFeatureInfoService.getFeatureInfoTextPlain(session,rq,rp,wmsParams);
			
			//保存之前，先删除上次保存的
			wmsCommService.deleteFile(textMap.get(i-1),basePath,saveDir);
			//保存图片
			wmsCommService.saveFile(textName,buffer, basePath,saveDir);
			return 3;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			
		}
		return 0;
	}
	
	@ResponseBody
	@RequestMapping(value="/getText.do")
	public String getSVG(HttpServletResponse rp,HttpServletRequest rq){
		try{
			String picName = textMap.get(i);
			i++;
			byte [] buff = wmsCommService.getFile(picName,basePath,saveDir);
			rp.setContentType("text/plain");
			rp.getOutputStream().write(buff);
			rp.getOutputStream().flush();
			rp.getOutputStream().close();
		}catch(Exception e){
			e.printStackTrace();
		}
		return "success";
	}
}
